# detect tapping or shaking and emit a 5

# We have already detected a shake events x events ago
_detected_shake_events_ago = 0
# and won't detect another one for at least y events
_dont_detect_shake_for = 10
def _detect_shake(block, key):
    global _detected_shake_events_ago
    if 0 < _detected_shake_events_ago < _dont_detect_shake_for:
        _detected_shake_events_ago += 1
        # block out acceleration sensors
        for c in "xyz":
            block[0][c] = 0.0
        return block
    if _detected_shake_events_ago >= _dont_detect_shake_for:
        _detected_shake_events_ago = 0
    if _do_detect_shake(block):
        _detected_shake_events_ago = 1
        if "k" not in block[0]:
            block[0]["k"] = key
        else:
            block[0]["k"] += key
        # block out acceleration sensors
        for c in "xyz":
            block[0][c] = 0.0
    return block

_shake_range = 3
_shake_detection_abs_threshold = 8.0
_shake_detection_sum_threshold = -1.0
def _do_detect_shake(block):
    absdiffs, sumdiffs = [], []
    for i in range(_shake_range):
        absdiffs.append({"x":0.0, "y":0.0, "z":0.0})
        sumdiffs.append({"x":0.0, "y":0.0, "z":0.0})
        for c in "xyz":
            absdiffs[i][c] += abs(block[i][c] - block[i+1][c])
            sumdiffs[i][c] += (block[i][c] - block[i+1][c])    
    absdiffskey, sumdiffskey = {}, {}
    sum_absdiffskey, sum_sumdiffskey = 0.0, 0.0
    for c in "xyz":
        absdiffskey[c] = sum([absdiffs[i][c] for i in range(_shake_range)])
        sumdiffskey[c] = sum([sumdiffs[i][c] for i in range(_shake_range)])
        sum_absdiffskey += absdiffskey[c]
        sum_sumdiffskey += sumdiffskey[c]
    if (sum_absdiffskey >= _shake_detection_abs_threshold and
        sum_sumdiffskey <= _shake_detection_sum_threshold):
        # print sum_absdiffskey, sum_sumdiffskey, absdiffskey, sumdiffskey
        return True
    else:
        return False
        

def _detect_tap(block, key):
    return block

def tapshake5(block):
    return _detect_tap(_detect_shake(block, "5"), "5")

